<template>
  <view class="personal-info-container">
    <nav-header title="个人信息"></nav-header>
    
    <view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
      <!-- Avatar Upload -->
      <view class="avatar-upload">
        <view class="avatar" @click="chooseAvatar">
          <image v-if="formData.avatarImageUrl" :src="formData.avatarImageUrl" mode="aspectFill"></image>
          <view v-else class="placeholder">
            <u-icon name="camera-fill" size="32" color="#ccc"></u-icon>
          </view>
        </view>
        <view class="tips">点击上传头像</view>
      </view>
      
      <!-- Form -->
      <view class="form-container">
        <!-- Name -->
        <view class="form-item">
          <view class="label required">姓名</view>
          <view class="input-wrap">
            <input 
              type="text" 
              v-model="formData.name" 
              placeholder="请输入您的姓名"
              maxlength="20"
            />
          </view>
        </view>
        
        <!-- Gender -->
        <view class="form-item">
          <view class="label required">性别</view>
          <view class="gender-select">
            <view 
              class="gender-option" 
              :class="{ 'active': formData.gender === 'male' }"
              @click="formData.gender = 'male'"
            >
              <text>男</text>
              <view v-if="formData.gender === 'male'" class="check-icon">
                <u-icon name="checkbox-mark" color="#5ac725" size="14"></u-icon>
              </view>
            </view>
            <view 
              class="gender-option" 
              :class="{ 'active': formData.gender === 'female' }"
              @click="formData.gender = 'female'"
            >
              <text>女</text>
              <view v-if="formData.gender === 'female'" class="check-icon">
                <u-icon name="checkbox-mark" color="#5ac725" size="14"></u-icon>
              </view>
            </view>
          </view>
        </view>
		
		<!-- maritalStatus -->
		<view class="form-item">
		  <view class="label">婚姻状况</view>
		  <view class="gender-select">
		    <view 
		      class="gender-option" 
		      :class="{ 'active': formData.maritalStatus === 'isMarital' }"
		      @click="formData.maritalStatus = 'isMarital'"
		    >
		      <text>已婚</text>
		      <view v-if="formData.maritalStatus === 'isMarital'" class="check-icon">
		        <u-icon name="checkbox-mark" color="#5ac725" size="14"></u-icon>
		      </view>
		    </view>
		    <view 
		      class="gender-option" 
		      :class="{ 'active': formData.maritalStatus === 'unMarital' }"
		      @click="formData.maritalStatus = 'unMarital'"
		    >
		      <text>未婚</text>
		      <view v-if="formData.maritalStatus === 'unMarital'" class="check-icon">
		        <u-icon name="checkbox-mark" color="#5ac725" size="14"></u-icon>
		      </view>
		    </view>
		  </view>
		</view>
        
        <!-- Birthday -->
        <view class="form-item">
          <view class="label required">出生日期</view>
          <view class="input-wrap date-picker" @click="showDatePicker = true">
            <!-- :class="{ 'placeholder': !formData.birthday }" -->
            <text>
              {{ formData.birthday || '请选择出生日期' }}
            </text>
            <u-icon name="calendar" color="#ccc" size="20"></u-icon>
          </view>
        </view>
        
        <!-- currentCity -->
        <view class="form-item">
          <view class="label required">现住城市</view>
          <view class="input-wrap region-picker" @click="showRegionPicker = true">
            <!-- :class="{ 'placeholder': !formData.currentCity }" -->
            <text>
              {{ formData.currentCity || '请选择所在地区' }}
            </text>
            <u-icon name="map" color="#ccc" size="20"></u-icon>
          </view>
        </view>
        
        <!-- Phone -->
        <view class="form-item">
          <view class="label required">手机号码</view>
          <view class="input-wrap">
            <input 
              type="number" 
              v-model="formData.phone" 
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </view>
        </view>
        
        <!-- Email -->
        <view class="form-item">
          <view class="label required">邮箱</view>
          <view class="input-wrap">
            <input 
              type="text" 
              v-model="formData.email" 
              placeholder="请输入您的邮箱"
              maxlength="50"
            />
          </view>
        </view>
		
		<!-- ethnicGroup -->
		<view class="form-item">
		  <view class="label">民族</view>
		  <view class="input-wrap">
		    <input 
		      type="text" 
		      v-model="formData.ethnicGroup" 
		      placeholder="请输入您的民族"
		      maxlength="50"
		    />
		  </view>
		</view>
		
		<!-- politicalStatus -->
		<view class="form-item">
		  <view class="label">政治面貌</view>
		  <view class="input-wrap">
		    <input 
		      type="text" 
		      v-model="formData.politicalStatus" 
		      placeholder="请输入您的政治面貌"
		      maxlength="50"
		    />
		  </view>
		</view>
      </view>
    </view>
    
    <!-- Save Button -->
    <view class="action-bar">
      <button class="save-btn" @click="savePersonalInfo">保存</button>
    </view>
    
    <!-- Date Picker -->
    <u-datetime-picker
      :show="showDatePicker"
      mode="date"
      :min-date="minDate"
      :max-date="maxDate"
      v-model="pickedDate"
      @confirm="confirmDate"
      @cancel="showDatePicker = false"
    ></u-datetime-picker>
    
    <!-- Region Picker -->
    <u-picker
      :show="showRegionPicker"
      ref="regionRef"
      :columns="regionColumns"
      @confirm="confirmRegion"
       @change="changeHandler"
      @cancel="showRegionPicker = false"
    ></u-picker>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useResumeStore } from '@/store/resume.js'
import NavHeader from '@/components/nav-header.vue'
import { onLoad } from '@dcloudio/uni-app'
import { 
  getPersonalInfo, 
  getPersonalInfoDetail, 
  addPersonalInfo, 
  updatePersonalInfo, 
  deletePersonalInfo,
  uploadAvatar 
} from '@/api/edit/personal.js'
import { getRegionTree } from '@/api/ai.js'
import env from '@/env'
import { globalHeaders } from '@/utils/auth';
	
const resumeStore = useResumeStore()
const statusBarHeight = ref(20)
const isEditing = ref(false)
const personalInfoId = ref(null)

// 表单数据
const formData = reactive({
  name: '',
  gender: 'male',
  maritalStatus: 'unMarital',
  birthday: '',
  currentCity: '',
  phone: '',
  email: '',
  ethnicGroup: '',
  politicalStatus: '',
  avatarImageUrl: '',
  resumeId: resumeStore.resumeId
})

// 日期选择器相关
const showDatePicker = ref(false)
const pickedDate = ref(new Date('1990-01-01'))
const minDate = new Date('1950-01-01')
const maxDate = new Date()
const uploadImg = ref(false)

// 地区选择器相关
const showRegionPicker = ref(false)
const cityList = ref([])
const regionColumns = ref([])
const columnData = ref([])
const isAdding = ref(false)
const currentId = ref('')
const regionRef = ref(null)

onLoad(async (options) => {
	console.log(options)
	if (options.index) {
		// 编辑模式，获取详情
		isAdding.value = false
		currentId.value = options.index
		await getPersonalDetail(options.index)
	} else {
		isAdding.value = true
	}
	uploadImg.value = false
	// 加载城市列表
	loadCityList()
})

onMounted(() => {
  // formData.resumeId = '1916784587136589826'
  formData.resumeId = resumeStore.resumeId
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  // 初始化日期选择器
  if (formData.birthday) {
    pickedDate.value = new Date(formData.birthday)
  }
})

// 获取个人信息详情
const getPersonalDetail = async (id) => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    const res = await getPersonalInfoDetail(id)
    if (res.code === 200) {
      Object.assign(formData, res.data)
      // 更新日期选择器
      if (formData.birthday) {
        pickedDate.value = new Date(formData.birthday)
      }
    }
  } catch (error) {
    console.error('获取个人信息详情失败', error)
  } finally {
    uni.hideLoading()
  }
}

const getCityList = async (arr) => {
  let arr1 = []
  let arr2 = []

  arr.forEach(item => {
    arr1.push(item.sname); // 收集省份简称
    if(item.children && item.children.length > 0){
      // 为每个省份创建一个子数组，存储其城市简称
      const cities = item.children.map(city => city.sname);
      arr2.push(cities);
    }
  })
  return [arr1,arr2]
}

// 加载城市列表
const loadCityList = async () => {
  try {
    uni.showLoading({
      title: '加载地区数据...'
    })
    
    const res = await getRegionTree()
    
    if (res.code == 200) { 
      const [province, city] = await getCityList(res.data)
      regionColumns.value = [province,city[0]]
      columnData.value = city
    } else {
      // 使用默认数据兜底
      regionColumns.value = [
        ['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '武汉市', '成都市', '重庆市', '西安市', '苏州市', '天津市', '青岛市', '郑州市', '宁波市', '济南市', '长沙市', '合肥市', '厦门市', '福州市']
      ]
      console.warn('接口返回的地区数据格式不符合预期，使用默认值')
    }
  } catch (error) {
    console.error('获取地区数据失败', error)
    uni.showToast({
      title: '获取地区数据失败',
      icon: 'none'
    })
    
    // 使用默认数据兜底
    regionColumns.value = [
      ['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '武汉市', '成都市', '重庆市', '西安市', '苏州市', '天津市', '青岛市', '郑州市', '宁波市', '济南市', '长沙市', '合肥市', '厦门市', '福州市']
    ]
  } finally {
    uni.hideLoading()
  }
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
		formData.avatarImageUrl = res.tempFilePaths[0]
		uploadImg.value = true
    }
  })
}

// 确认日期选择
const confirmDate = (e) => {
  showDatePicker.value = false
  const date = new Date(e.value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  formData.birthday = `${year}-${month}-${day}`
}

// 确认地区选择
const confirmRegion = (e) => {
  showRegionPicker.value = false
  formData.currentCity = e.value[1]
}

const changeHandler = (e) => {
  const {
    columnIndex,
    value,
    values,
    index,
  } = e;
  if (columnIndex == '0') {
    regionRef.value.setColumnValues(1, columnData.value[index]);
  }
}

// 保存个人信息
const savePersonalInfo = async () => {
  // 校验必填项
  if (!formData.name) {
    return uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    })
  }
  
  if (!formData.phone) {
    return uni.showToast({
      title: '请输入手机号码',
      icon: 'none'
    })
  }
  
  // 校验手机号格式
  if (!/^1\d{10}$/.test(formData.phone)) {
    return uni.showToast({
      title: '请输入正确的手机号码',
      icon: 'none'
    })
  }
  
  // 校验邮箱格式(如果有填写)
  if (formData.email && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(formData.email)) {
    return uni.showToast({
      title: '请输入正确的邮箱地址',
      icon: 'none'
    })
  }
  
  if (!formData.birthday) {
    return uni.showToast({
      title: '请选择出生日期',
      icon: 'none'
    })
  }
  
  if (!formData.currentCity) {
    return uni.showToast({
      title: '请选择现住城市',
      icon: 'none'
    })
  }
  
  try {
    uni.showLoading({
      title: '保存中...'
    })
	if(uploadImg.value == true){
		uni.uploadFile({
			url: `${env.baseURL}/resource/oss/upload/compress`,
			header: globalHeaders(),
			filePath: formData.avatarImageUrl,
			name: 'file',
			success: async (uploadFileRes) => {
				let data = JSON.parse(uploadFileRes.data).data
				// 准备请求参数
				const params = {
				  ...formData,
				  resumeId: resumeStore.resumeId,
				 }
				 params.avatarImageUrl = data.url
				 params.avatarImageUrlId = data.ossId
				subMit(params)
			}
		});
	}else {
		// 准备请求参数
		const params = {
		  ...formData,
		  resumeId: resumeStore.resumeId,
		 }
		subMit(params)
	}
  } catch (error) {
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

const subMit = async (params) => {
	let res
	if (!isAdding.value) {
	  // 更新个人信息
	  params.id = currentId.value
	  res = await updatePersonalInfo(params)
	} else {
	  // 新增个人信息
	  res = await addPersonalInfo(params)
	}
	
	if (res.code === 200) {
	  // 更新Store
	  resumeStore.setPersonalInfo(formData)
	  
	  uni.showToast({
		title: '保存成功',
		icon: 'success'
	  })
	  
	  // 延迟返回
	  setTimeout(() => {
		uni.navigateBack()
	  }, 1500)
	} else {
	  uni.showToast({
		title: res.msg || '保存失败',
		icon: 'none'
	  })
	}
}
</script>

<style lang="scss" scoped>
.personal-info-container {
  min-height: 100vh;
  background-color: #FFFFFF;
  display: flex;
  flex-direction: column;
  
  .content {
    flex: 1;
    padding: 20px;
    padding-bottom: 70px;
    
    .avatar-upload {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 24px;
      
      .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;
        background-color: #f0f0f0;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 8px;
        
        image {
          width: 100%;
          height: 100%;
        }
        
        .placeholder {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 100%;
        }
      }
      
      .tips {
        font-size: 14px;
        color: #999;
      }
    }
    
    .form-container {
      
      .form-item {
        margin-bottom: 24px;
        
        .label {
          font-size: 16px;
          color: #333;
          margin-bottom: 10px;
          display: block;
          font-weight: 500;
          
          &.required::after {
            content: '*';
            color: #ff4d4f;
            margin-left: 4px;
          }
        }
        
        .input-wrap {
          border-bottom: 1px solid #e5e5e5;
          height: 44px;
          display: flex;
          align-items: center;
          
          input {
            flex: 1;
            height: 100%;
            font-size: 16px;
            color: #333;
          }
          
          &.date-picker, &.region-picker {
            justify-content: space-between;
            
            text {
              font-size: 16px;
              color: #333;
              
              &.placeholder {
                color: #999;
              }
            }
          }
        }
        
        .textarea-wrap {
          border: 1px solid #e5e5e5;
          border-radius: 4px;
          padding: 12px;
          
          textarea {
            width: 100%;
            font-size: 15px;
            color: #333;
            min-height: 80px;
          }
        }
        
        .gender-select {
          display: flex;
          
          .gender-option {
            flex: 1;
            height: 44px;
            border: 1px solid #e5e5e5;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            margin-right: 12px;
            
            &:last-child {
              margin-right: 0;
            }
            
            &.active {
              border-color: #5ac725;
              
              text {
                color: #5ac725;
              }
            }
            
            text {
              font-size: 15px;
              color: #333;
            }
            
            .check-icon {
              position: absolute;
              top: -1px;
              right: -1px;
              width: 16px;
              height: 16px;
              background-color: #5ac725;
              border-top-right-radius: 6px;
              border-bottom-left-radius: 6px;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }
        }
      }
    }
  }
  
  .action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px 20px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 9;
    
    .save-btn {
      width: 100%;
      height: 44px;
      line-height: 44px;
      background-color: #5ac725;
      color: #fff;
      font-size: 16px;
      font-weight: 500;
      border-radius: 22px;
    }
  }
}
</style> 